import socket

# 创建一个TCP服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#  将SO_REUSEADDR 设置为1，表示重复使用此端口，避免出现address already In use错误。
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 将套接字的地址设置为127.0.0.1:8000
address = ("127.0.0.1", 8000)
server_socket.bind(address)
# 开启监听传入的连接
server_socket.listen()
# 创建非阻塞套接字
server_socket.setblocking(False)
try:

    connections = []
    while True:
        # 捕获并忽略阻塞I/O错误
        # 但是这样，会一直遍历下去，会极其耗费CPU资源。
        try:
            # 等待连接
            connection, client_address = server_socket.accept()
            # 将客户端套接字标记为非阻塞
            connection.setblocking(False)
            print(f"从{client_address}获取一个连接")
            connections.append(connection)
        except:
            pass

        for connection in connections:
            buffer = b""
            while buffer[-2:] != b"\r\n":
                data = connection.recv(2)
                if not data:
                    break
                else:
                    print(f"获取数据：{data}")
                    buffer += data
            connection.sendall(buffer)
finally:
    server_socket.close()
